import os
import re
from string import whitespace

import cv2
import numpy as np
import skimage.io as io


def concatimg(mode, nameflg, path, out_path, new_dir, file_name, h_multiple, w_multiple, repeaflage,move_right):
    try:
        lgz = io.imread(path)  # np.ndarray, [h, w, c], 值域(0, 255), RGB
        print(lgz.shape)  # 查看图片的大小
        print(lgz.dtype)  # 查看数组元素数据类型
        flg = ''
        if lgz.shape[0] > lgz.shape[1]:
            if mode == 2:
                return
            flg = "-h"

        if lgz.shape[0] <= lgz.shape[1]:
            if mode == 1:
                return
            new_dir += "-w"
        pj1 = np.zeros((lgz.shape[0] * h_multiple, lgz.shape[1] * w_multiple, lgz.shape[2]))
        if repeaflage == 0:
            pj1[:lgz.shape[0], move_right:move_right+lgz.shape[1], :] = lgz.copy()
        else:
            for h in range(h_multiple):
                for w in range(w_multiple):
                    pj1[lgz.shape[0] * h:lgz.shape[0] * (h + 1), lgz.shape[1] * w:lgz.shape[1] * (w + 1),
                    :] = lgz.copy()
        print(pj1.dtype)  # 查看数组元素类型
        pj1 = np.array(pj1, dtype=np.uint8)  # 将pj1数组元素数据类型的改为"uint8"
        if nameflg == 1:
            new_dir += flg
        if not os.path.exists(os.path.join(out_path, new_dir)):
            os.makedirs(os.path.join(out_path, new_dir))
        out_file_path = os.path.join(out_path, new_dir, file_name)
        print("out_file_path:" + out_file_path)
        io.imsave(out_file_path, pj1)  # 保存拼接后的图片
    except Exception as e:
        print(e)


def copy(in_path, out_path, filename):  # 裁剪图片到分辨率（1080，1920）并保存到指定文件夹
    new_dir = os.path.basename(dirpath)
    if not os.path.exists(os.path.join(out_path, new_dir)):
        os.makedirs(os.path.join(out_path, new_dir))
    img = cv2.imread(os.path.join(in_path, filename))
    print(img.shape)
    if img.shape[0] < img.shape[1]:  # 高比宽小，横图
        cv2.imwrite(os.path.join(out_path, new_dir, filename), img)

def crop(in_path, out_path, filename):  # 裁剪图片到分辨率（1080，1920）并保存到指定文件夹
    new_dir = os.path.basename(dirpath)
    if not os.path.exists(os.path.join(out_path, new_dir)):
        os.makedirs(os.path.join(out_path, new_dir))
    img = cv2.imread(os.path.join(in_path, filename))
    print(img.shape)
    if img.shape[0] < img.shape[1]:  # 高比宽小，横图
        h_cut = int((img.shape[0] - img.shape[1] / 1920 * 1080) / 2)
        cropimg = img[h_cut:img.shape[0] - h_cut, 0:img.shape[1]]
        cv2.imwrite(os.path.join(out_path, new_dir, filename), cropimg)


def crop_1(inputfilepath):  # 裁剪图片到分辨率（1080，1920）并替换
    img = cv2.imread(inputfilepath)
    print(img.shape)
    if img.shape[0] < img.shape[1]:  # 高比宽小，横图
        h_cut = int((img.shape[0] - img.shape[1] / 1920 * 1080) / 2)
        cropimg = img[h_cut:img.shape[0] - h_cut, 0:img.shape[1]]
        cv2.imwrite(inputfilepath, cropimg)


def rename(file_path):
    for dirpath, dirnames, filenames in os.walk(file_path):
        for filename in filenames:
            try:
                inputfilename = dirpath.replace("\\", "/") + '/' + filename
                tables = str.maketrans('', '', "()【】-  */" + r"""!"#$%&'()*+，,-/:;<=>?@[\]^_`{|}~""" + whitespace)
                # 去除中文
                pattern = re.compile(u"[\u4e00-\u9fa5]+")
                filename = re.sub(pattern, "", filename)
                outfilename = dirpath.replace("\\", "/") + '/' + str.strip(filename.translate(tables))
                print('inputfilename:' + inputfilename)
                print('outfilename:' + outfilename)
                if not inputfilename.__eq__(outfilename) and os.path.exists(outfilename):
                    os.remove(outfilename)
                os.rename(inputfilename, outfilename)
            except FileExistsError as f:
                print(f)
                continue


if __name__ == "__main__":
    path = r'D:\like\picture\202305'
    out_path = r'D:\like\picture\202305'
    # path = r'D:\picture'
    # out_path = r'D:\desktop1'
    mode = 1  # 1 仅处理竖图 2 仅处理横图 3 处理所有图片
    nameflg = 2  # 1 表示需要拼接竖图 横图标识 2 不需要拼接标识
    h_multiple = 1  # h_multiple 新图片高度是旧图片高度多少倍
    w_multiple = 3  # w_multiple 新图片宽度是旧图片宽度多少倍
    repeaflage = 0  # repeaflage 拼接图片是图片自身是否重复，0 不重复 1重复
    move_right = 0  # 右移多少像素
    if not os.path.exists(out_path):
        os.makedirs(out_path)
    rename(path)
    with ThreadPoolExecutor(max_workers=5) as f:
        for dirpath, dirnames, filenames in os.walk(path):
            for filename in filenames:
                try:
                    if filename.endswith(".jpg") or filename.endswith(".png"):

                        inputfilepath = os.path.join(dirpath, filename)
                        print(inputfilepath)
                        new_dir = os.path.basename(dirpath)
                        f.submit(concatimg, mode, nameflg, inputfilepath, out_path, new_dir, filename, h_multiple,
                                 w_multiple, repeaflage,move_right)

                        # inputfilepath = os.path.join(dirpath, filename)
                        # print(inputfilepath)
                        # f.submit(crop_1, inputfilepath)

                        # f.submit(crop, dirpath, out_path, filename)

                        # copy(dirpath, out_path, filename)

                        # os.remove(inputfilename)  # 如果不删除原图则注释掉该行
                except Exception as ff:
                    print(ff)
                    continue
